package com.example.computer_component_manager.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Toast
import com.android.volley.Request
import com.example.computer_component_manager.R
import com.example.computer_component_manager.bean.AdminUserInfo
import com.example.computer_component_manager.databinding.ActivityLoginBinding
import com.example.computer_component_manager.util.DbUtil
import com.example.computer_component_manager.volley.MyJsonObjectRequest
import com.example.computer_component_manager.volley.VolleyApplication

/**
 * 登录界面
 *
 * @author 1923111015董寺卓
 */

class LoginActivity : Activity() {

    companion object {
        const val DEFAULT_USERNAME = "admin"
        const val DEFAULT_PASSWORD = "admin"
    }

    private lateinit var binding: ActivityLoginBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityLoginBinding.inflate(layoutInflater)
        super.onCreate(savedInstanceState)
        setContentView(binding.root)
        checkLogin()
        binding.etLoginUsername.setText(DEFAULT_USERNAME)
        binding.etLoginPassword.setText(DEFAULT_PASSWORD)

    }

    private fun checkLogin() {
        val checkLoginRequest =
            MyJsonObjectRequest(Request.Method.GET, "${DbUtil.API_PREFIX}/admin/check",
                null, {
                    DbUtil.loginAdminUserInfo =
                        DbUtil.gson.fromJson(it.toString(), AdminUserInfo::class.java)
                    login()
                }, {
                    Toast.makeText(this, resources.getText(R.string.auto_login_failed),
                        Toast.LENGTH_SHORT).show()
                })
        VolleyApplication.instance.requestQueue.add(checkLoginRequest)
    }

    fun login() {
        Toast.makeText(this, "登录成功！", Toast.LENGTH_SHORT).show()
        val intent = Intent(this, MenuActivity::class.java)
        startActivity(intent)
        finish()
    }

    fun clickLogin(view: View) {
        if (view.id == R.id.btnLogin) {
            if (binding.etLoginUsername.text.isNotEmpty()
                && binding.etLoginPassword.text.isNotEmpty()
            ) {
                DbUtil.validateAdminUserInfo(this,
                    binding.etLoginUsername.text.toString(),
                    binding.etLoginPassword.text.toString()
                )
            } else {
                Toast.makeText(this, resources.getString
                    (R.string.empty_username_or_password_message), Toast.LENGTH_SHORT).show()
            }
        }
    }
}